package library.admin.service.impl;

import library.admin.config.FileUploadConfig;
import library.admin.service.IFileService;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件服务实现类
 *
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class FileServiceImpl implements IFileService {

    private final FileUploadConfig fileUploadConfig;


    @Override
    public String uploadBookCover(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        // 获取文件名及扩展名
        String originalFilename = file.getOriginalFilename();
        String extName = FileUtil.extName(originalFilename);
        
        // 检查是否为图片文件
        String[] allowedExtensions = {"jpg", "jpeg", "png", "gif", "bmp"};
        boolean isValidExtension = false;
        for (String ext : allowedExtensions) {
            if (ext.equalsIgnoreCase(extName)) {
                isValidExtension = true;
                break;
            }
        }
        
        if (!isValidExtension) {
            throw new IllegalArgumentException("只允许上传jpg、jpeg、png、gif、bmp格式的图片");
        }
        
        // 生成新文件名，避免文件名冲突
        String newFilename = IdUtil.fastSimpleUUID() + "." + extName;
        
        // 获取当前工作目录的绝对路径
        String currentDir = System.getProperty("user.dir");
        // 构建完整的文件路径
        String bookCoverPath = currentDir + File.separator + fileUploadConfig.getUploadPath();
        
        log.info("上传路径配置为: {}", bookCoverPath); // 添加日志记录上传路径
        
        try {
            // 使用Java NIO创建目录，更可靠的方式
            Path dirPath = Paths.get(bookCoverPath);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
                log.info("成功创建目录: {}", dirPath.toAbsolutePath());
            } else {
                log.info("目录已存在: {}", dirPath.toAbsolutePath());
            }
            
            // 保存文件
            Path filePath = Paths.get(bookCoverPath, newFilename);
            log.info("保存文件到: {}", filePath.toAbsolutePath());
            
            // 将上传的文件数据写入到目标文件
            Files.write(filePath, file.getBytes());
            
            // 返回文件的访问URL
            return fileUploadConfig.getAccessUrlPrefix() + "/"  + newFilename;
        } catch (IOException e) {
            log.error("文件上传失败: 路径={}, 错误={}", bookCoverPath, e.getMessage(), e);
            throw new IOException("文件保存失败: " + e.getMessage() + ", 路径: " + bookCoverPath, e);
        }
    }

    @Override
    public boolean deleteBookCover(String coverUrl) {
        if (StrUtil.isBlank(coverUrl)) {
            return false;
        }
        
        // 从URL中提取文件名
        String filename = coverUrl.substring(coverUrl.lastIndexOf("/") + 1);
        
        // 获取当前工作目录的绝对路径
        String currentDir = System.getProperty("user.dir");
        // 构建完整的文件路径
        String filePath = currentDir + File.separator + fileUploadConfig.getUploadPath() + File.separator + filename;
        
        log.debug("删除文件: {}", filePath);
        
        try {
            Path path = Paths.get(filePath);
            if (Files.exists(path)) {
                Files.delete(path);
                return true;
            }
            return false;
        } catch (IOException e) {
            log.error("删除文件失败: {}", e.getMessage(), e);
            return false;
        }
    }
} 